package cn.htsyb.synergy.utils;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 *
 * @author lakeside hubin_yuan.410@hotmail.com
 * @version V1.0.0
 * @since 1.0
 * @date 2022/5/11
 */
public class IPUtil {
    private static InetAddress localHost;

    static {
        try {
            localHost = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将IP4地址转换为Long
     *
     * @param ip
     * @return
     */
    public static Long ip4ToLong(String ip) {
        Long ips = 0L;
        String[] numbers = ip.split("\\.");
        for (int i = 0; i < 4; ++i) {
            ips = ips << 8 | Integer.parseInt(numbers[i]);
        }
        return ips;
    }

    /**
     * 将Long转换为IP4地址
     *
     * @param number
     * @return
     */
    public static String longToIp4(Long number) {
        String ip = "";
        for (int i = 3; i >= 0; i--) {
            ip = ip + (number & 0xff);
            if (i != 0) {
                ip += ".";
            }
            number = number >> 8;
        }

        return ip;
    }

    /**
     * 获得本机IP
     *
     * @return
     * @throws UnknownHostException
     */
    public static String getLocalHost() {
        return localHost != null ? localHost.getHostAddress() : "";
    }

    /**
     * 获得本机名称
     *
     * @return
     * @throws UnknownHostException
     */
    public static String getLocalHostName() {
        return localHost != null ? localHost.getHostName() : "";
    }
}
